package jou.cs.service.impl;

import jou.cs.configurator.CONST;
import jou.cs.entity.Place_type;
import jou.cs.entity.TPlace;
import jou.cs.mapper.PlaceRepository;
import jou.cs.mapper.Place_typeRepository;
import jou.cs.service.CommentService;
import jou.cs.service.PlaceService;
import jou.cs.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PlaceImpl implements PlaceService {
    @Resource
    private PlaceRepository repository;
    @Resource
    private Place_typeRepository typeRepository;

    @Resource
    private QuestionService questionService;
    @Autowired
    private CommentService commentService;

    @Override
    public void addPlace(TPlace place) {
        repository.save(place);
    }

    @Override
    public void deletePlace(Long id) {
        repository.deleteById(id);
    }

    @Override
    public void updatePlace(TPlace place) {
        repository.save(place);
    }

    @Override
    public Map<Object, Object> getPlaceById(Long id) {
        TPlace place = repository.findById(id).orElse(null);
        if (place == null)
            throw new RuntimeException("没有找到该地点");

        Map<Object, Object> map = new HashMap<>();
        map.put("place", place);
        map.put("qus", questionService.getQusByPid(id).stream().limit(5).collect(Collectors.toList()));
        map.put("coms", commentService.getComByPid(id).stream().limit(5).collect(Collectors.toList()));


        return map;
    }

    @Override
    public Page<TPlace> getPlaceByPage(int page) {
        // page
        return repository.findAll(PageRequest.of(page, CONST.PAGE_SIZE));
    }

    @Override
    public void addType(Long pid, Long tid) {
        Place_type type = Place_type.builder()
                .tid(tid).pid(pid)
                .build();
        typeRepository.save(type);
    }
}
